module Poro
  module Util
    # The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without,
    # and class names to foreign keys. The default inflections for pluralization, singularization, and uncountable words are kept
    # in inflections.rb.
    #
    # The Rails core team has stated patches for the inflections library will not be accepted
    # in order to avoid breaking legacy applications which may be relying on errant inflections.
    # If you discover an incorrect inflection and require it for your application, you'll need
    # to correct it yourself (explained below).
    module Inflector
      extend self

      # By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+
      # is set to <tt>:lower</tt> then +camelize+ produces lowerCamelCase.
      #
      # +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces.
      #
      # Examples:
      #   "active_record".camelize                # => "ActiveRecord"
      #   "active_record".camelize(:lower)        # => "activeRecord"
      #   "active_record/errors".camelize         # => "ActiveRecord::Errors"
      #   "active_record/errors".camelize(:lower) # => "activeRecord::Errors"
      #
      # As a rule of thumb you can think of +camelize+ as the inverse of +underscore+,
      # though there are cases where that does not hold:
      #
      #   "SSLError".underscore.camelize # => "SslError"
      def camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true)
        if first_letter_in_uppercase
          lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
        else
          lower_case_and_underscored_word.to_s[0].chr.downcase + camelize(lower_case_and_underscored_word)[1..-1]
        end
      end

      # Makes an underscored, lowercase form from the expression in the string.
      #
      # Changes '::' to '/' to convert namespaces to paths.
      #
      # Examples:
      #   "ActiveRecord".underscore         # => "active_record"
      #   "ActiveRecord::Errors".underscore # => active_record/errors
      #
      # As a rule of thumb you can think of +underscore+ as the inverse of +camelize+,
      # though there are cases where that does not hold:
      #
      #   "SSLError".underscore.camelize # => "SslError"
      def underscore(camel_cased_word)
        word = camel_cased_word.to_s.dup
        word.gsub!(/::/, '/')
        word.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
        word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
        word.tr!("-", "_")
        word.downcase!
        word
      end

      # Replaces underscores with dashes in the string.
      #
      # Example:
      #   "puni_puni" # => "puni-puni"
      def dasherize(underscored_word)
        underscored_word.gsub(/_/, '-')
      end

      # Removes the module part from the expression in the string.
      #
      # Examples:
      #   "ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections"
      #   "Inflections".demodulize                                       # => "Inflections"
      def demodulize(class_name_in_module)
        class_name_in_module.to_s.gsub(/^.*::/, '')
      end

      # Creates a foreign key name from a class name.
      # +separate_class_name_and_id_with_underscore+ sets whether
      # the method should put '_' between the name and 'id'.
      #
      # Examples:
      #   "Message".foreign_key        # => "message_id"
      #   "Message".foreign_key(false) # => "messageid"
      #   "Admin::Post".foreign_key    # => "post_id"
      def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
        underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
      end

      # Ruby 1.9 introduces an inherit argument for Module#const_get and
      # #const_defined? and changes their default behavior.
      if Module.method(:const_get).arity == 1
        # Tries to find a constant with the name specified in the argument string:
        #
        #   "Module".constantize     # => Module
        #   "Test::Unit".constantize # => Test::Unit
        #
        # The name is assumed to be the one of a top-level constant, no matter whether
        # it starts with "::" or not. No lexical context is taken into account:
        #
        #   C = 'outside'
        #   module M
        #     C = 'inside'
        #     C               # => 'inside'
        #     "C".constantize # => 'outside', same as ::C
        #   end
        #
        # NameError is raised when the name is not in CamelCase or the constant is
        # unknown.
        def constantize(camel_cased_word)
          names = camel_cased_word.split('::')
          names.shift if names.empty? || names.first.empty?

          constant = Object
          names.each do |name|
            constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name)
          end
          constant
        end
      else
        def constantize(camel_cased_word) #:nodoc:
          names = camel_cased_word.split('::')
          names.shift if names.empty? || names.first.empty?

          constant = Object
          names.each do |name|
            constant = constant.const_defined?(name, false) ? constant.const_get(name) : constant.const_missing(name)
          end
          constant
        end
      end

      # Turns a number into an ordinal string used to denote the position in an
      # ordered sequence such as 1st, 2nd, 3rd, 4th.
      #
      # Examples:
      #   ordinalize(1)     # => "1st"
      #   ordinalize(2)     # => "2nd"
      #   ordinalize(1002)  # => "1002nd"
      #   ordinalize(1003)  # => "1003rd"
      def ordinalize(number)
        if (11..13).include?(number.to_i % 100)
          "#{number}th"
        else
          case number.to_i % 10
            when 1; "#{number}st"
            when 2; "#{number}nd"
            when 3; "#{number}rd"
            else    "#{number}th"
          end
        end
      end
    end
  end
end